﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace LongSpeed.WebSite.Behaviors
{
    public class Memu
    {
        string _Name, _Desiption, _Memo;
        /// <summary>
        /// 编号
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name
        {
            get
            {
                if (_Name == null)
                {
                }
                return _Name;
            }
            set { _Name = value + ""; }
        }
        /// <summary>
        /// 排序索引
        /// </summary>
        public int SortIndex { get; set; }
        /// <summary>
        /// 上级编号
        /// </summary>   
        int pid = 0;
        public int ParentId
        {
            get
            {
                if (this.ParentMemu != null)
                {
                    pid = ParentMemu.ID;
                }
                return pid;
            }
            set { pid = value; }
        }
        /// <summary>
        /// 描述
        /// </summary>
        public string Description
        {
            get
            {
                if (_Desiption == null)
                {

                }
                return _Desiption;
            }
            set { _Desiption = value; }
        }
        /// <summary>
        /// 备注
        /// </summary>
        public string Memo
        {
            get
            {
                if (_Memo == null)
                {
                }
                return _Memo;
            }
            set { _Memo = value + ""; }
        }

        /// <summary>
        /// 是否显示
        /// </summary>
        public bool IsShow { get; set; }

        IList<Memu> _ChildMemu = null;

        /// <summary>
        /// 子菜单
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public IList<Memu> ChildMemu
        {
            get
            {
                if (_ChildMemu == null)
                {
                    _ChildMemu = new List<Memu>();
                    _ChildMemu = this.GetMemu(this, false);
                }
                return _ChildMemu;
            }
            set { _ChildMemu = value; }
        }

        Memu _ParentMemu;
        [Newtonsoft.Json.JsonIgnore]
        public Memu ParentMemu
        {
            get
            {
                if (_ParentMemu == null)
                {
                    _ParentMemu = new Memu();
                    _ParentMemu.Init(this.pid);
                }
                return _ParentMemu;
            }
            set { _ParentMemu = value; }
        }

        /// <summary>
        /// 说明标题
        /// </summary>
        public string AlternateField1 { get; set; }
        /// <summary>
        /// 备注标题
        /// </summary>
        public string AlternateField2 { get; set; }
        /// <summary>
        /// URL映射地址
        /// </summary>
        public string AlternateField3 { get; set; }
        /// <summary>
        /// URL映射ID
        /// </summary>
        public string AlternateField4 { get; set; }
        public bool AlternateField5 { get; set; }
        public string AlternateField6 { get; set; }

        public IList<Memu> GetMemu()
        {
            IList<Memu> memus = new List<Memu>();

            string where = " ParentId = 0 ";

            var ds = GetData(where);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Memu m = RowToEntity(row);
                    m.ChildMemu = GetMemu(m, false);

                    memus.Add(m);
                }
            }

            return memus;
        }
        public IList<Memu> GetMemu(Memu parMemu, bool getOnlyShow)
        {
            IList<Memu> memus = new List<Memu>();

            string where = parMemu == null ? " ParentId = 0 " : string.Format(" ParentId = {0} ", parMemu.ID);
            if (getOnlyShow)
            {
                where += string.Format(" and IsShow = {0}", true);
            }

            var ds = GetData(where);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Memu m = RowToEntity(row);
                    m.ParentMemu = parMemu;


                    m.ChildMemu = GetMemu(m, getOnlyShow);

                    memus.Add(m);
                }
            }

            return memus;
        }

        private static Memu RowToEntity(DataRow row)
        {
            Memu m = new Memu()
            {
                Description = row["Desiption"] + "",
                ID = Convert.ToInt32(row["ID"]),
                Memo = row["Memo"] + "",
                Name = row["M_Name"] + "",
                ParentId = Convert.ToInt32(row["ParentId"]),
                SortIndex = Convert.ToInt32(row["SortIndex"]),
                IsShow = Convert.ToBoolean(row["IsShow"]),
                ParentMemu = null,
                AlternateField1 = row["AlternateField1"] + "",
                AlternateField2 = row["AlternateField2"] + "",
                AlternateField3 = row["AlternateField3"] + "",
                AlternateField4 = row["AlternateField4"] + "",
                AlternateField5 = row["AlternateField5"] + "" == "" ? true : Convert.ToBoolean(row["AlternateField5"]),
                AlternateField6 = row["AlternateField6"] + "",
            };
            return m;
        }
        public DataSet GetData(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" SELECT   ID, M_Name, SortIndex, ParentID, Desiption, [Memo],IsShow, AlternateField1,AlternateField2,AlternateField3,AlternateField4,AlternateField5,AlternateField6 FROM   T_Menus ");
            if (!string.IsNullOrEmpty(where))
            {
                strSql.Append(" where  " + where);
            }
            strSql.Append(" order by SortIndex ");
            return OleDbHelper.Query(strSql.ToString());
        }
        public void Init(int id)
        {
            string where = " ID =  " + id;

            var ds = GetData(where);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {

                    Memu m = RowToEntity(row);

                    this.Description = m.Description;
                    this.ID = m.ID;
                    this.Memo = m.Memo;
                    this.Name = m.Name;
                    var parentId = m.ParentId;
                    this.ParentMemu.Init(parentId);
                    this.SortIndex = m.SortIndex;
                    this.IsShow = m.IsShow;

                    this.AlternateField1 = m.AlternateField1;
                    this.AlternateField2 = m.AlternateField2;
                    this.AlternateField3 = m.AlternateField3;
                    this.AlternateField4 = m.AlternateField4;
                    this.AlternateField5 = m.AlternateField5;
                    this.AlternateField6 = m.AlternateField6;

                    break;
                }
            }
        }

        public bool Save()
        {
            object des, name, memo;
            object af1, af2, af3, af4, af5, af6;

            if (this.Description == null) des = DBNull.Value; else des = this.Description;
            if (this.Name == null) name = DBNull.Value; else name = this.Name;
            if (this.Memo == null) memo = DBNull.Value; else memo = this.Memo;

            if (this.AlternateField1 == null) af1 = DBNull.Value; else af1 = this.AlternateField1;
            if (this.AlternateField2 == null) af2 = DBNull.Value; else af2 = this.AlternateField2;
            if (this.AlternateField3 == null) af3 = DBNull.Value; else af3 = this.AlternateField3;
            if (this.AlternateField4 == null) af4 = DBNull.Value; else af4 = this.AlternateField4;
            //if (this.AlternateField5 == null) af5 = DBNull.Value; else af5 = this.AlternateField5;
            if (this.AlternateField6 == null) af6 = DBNull.Value; else af6 = this.AlternateField6;

            UrlMapping urlMapping = new UrlMapping()
            {
                Args = this.ParentMemu.ID == 0 ? string.Format("pid={0}", this.ID) : string.Format("mid={0}&pid={1}", this.ID, this.ParentMemu.ID),
                FormAddress = this.AlternateField3,
                ToAddress = this.ParentMemu.ID == 0 ? "~/Main/RegionalServer.aspx" : "~/Main/EngineRoom.aspx",
                ID = this.AlternateField4 == "" ? 0 : Convert.ToInt32(this.AlternateField4)
            };

            string execSql = "";
            if (this.ID == 0)
            {
                if (!string.IsNullOrEmpty(urlMapping.FormAddress))
                {
                    urlMapping.Add(urlMapping);
                    af4 = urlMapping.ID;
                }
                this.AlternateField4 = urlMapping.ID + "";

                execSql = " insert into   T_Menus ( IsShow, [Memo], Desiption, ParentID, M_Name,SortIndex,AlternateField1,AlternateField2,AlternateField3,AlternateField4,AlternateField5,AlternateField6 ) values";
                execSql += "   (  @IsShow,  @Memo , @Desiption, @ParentID, @M_Name,@SortIndex,@AlternateField1,@AlternateField2,@AlternateField3,@AlternateField4,@AlternateField5,@AlternateField6) ";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {     
                    new System.Data.OleDb.OleDbParameter("@IsShow", System.Data.OleDb.OleDbType.Boolean){ Value = this.IsShow},             
                    new System.Data.OleDb.OleDbParameter("@Memo", System.Data.OleDb.OleDbType.LongVarWChar){ Value = memo}, 
                    new System.Data.OleDb.OleDbParameter("@Desiption", System.Data.OleDb.OleDbType.LongVarWChar){ Value = des},
                    new System.Data.OleDb.OleDbParameter("@ParentID" , System.Data.OleDb.OleDbType.Integer){ Value =this.ParentMemu.ID},
                    new System.Data.OleDb.OleDbParameter("@M_Name", System.Data.OleDb.OleDbType.VarWChar,255){ Value = name},
                    new System.Data.OleDb.OleDbParameter("@SortIndex", System.Data.OleDb.OleDbType.Integer){ Value = SortIndex},
                    new System.Data.OleDb.OleDbParameter("@AlternateField1", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af1},
                    new System.Data.OleDb.OleDbParameter("@AlternateField2", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af2},
                    new System.Data.OleDb.OleDbParameter("@AlternateField3", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af3},
                    new System.Data.OleDb.OleDbParameter("@AlternateField4", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af4},
                    new System.Data.OleDb.OleDbParameter("@AlternateField5", System.Data.OleDb.OleDbType.VarWChar,255){ Value = this.AlternateField5},
                    new System.Data.OleDb.OleDbParameter("@AlternateField6", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af6}
                };


                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    this.ID = OleDbHelper.GetMaxID("ID", "T_Menus");

                    return true;
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(urlMapping.FormAddress))
                {
                    urlMapping.Update(urlMapping);
                }

                execSql = " update  T_Menus set   IsShow = @IsShow,  Desiption=@Desiption, M_Name=@M_Name,SortIndex=@SortIndex,  [Memo]=@Memo, ";
                execSql += " AlternateField1 =@AlternateField1 , AlternateField2 =@AlternateField2 , AlternateField3 =@AlternateField3 , ";
                execSql += " AlternateField4 =@AlternateField4 , AlternateField5 =@AlternateField5 , AlternateField6 =@AlternateField6 ";
                execSql += " where ID = @ID";

                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                    new System.Data.OleDb.OleDbParameter("@IsShow", System.Data.OleDb.OleDbType.Boolean){ Value = this.IsShow},             
                    new System.Data.OleDb.OleDbParameter("@Desiption", System.Data.OleDb.OleDbType.LongVarWChar){ Value = des},
                    new System.Data.OleDb.OleDbParameter("@M_Name", System.Data.OleDb.OleDbType.VarWChar,255){ Value = name},
                    new System.Data.OleDb.OleDbParameter("@SortIndex", System.Data.OleDb.OleDbType.Integer){ Value = SortIndex},
                    new System.Data.OleDb.OleDbParameter("@Memo", System.Data.OleDb.OleDbType.LongVarWChar){ Value = memo}, 
                    new System.Data.OleDb.OleDbParameter("@AlternateField1", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af1},
                    new System.Data.OleDb.OleDbParameter("@AlternateField2", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af2},
                    new System.Data.OleDb.OleDbParameter("@AlternateField3", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af3},
                    new System.Data.OleDb.OleDbParameter("@AlternateField4", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af4},
                    new System.Data.OleDb.OleDbParameter("@AlternateField5", System.Data.OleDb.OleDbType.VarWChar,255){ Value = this.AlternateField5},
                    new System.Data.OleDb.OleDbParameter("@AlternateField6", System.Data.OleDb.OleDbType.VarWChar,255){ Value = af6},
                    new System.Data.OleDb.OleDbParameter("@ID", System.Data.OleDb.OleDbType.Integer){ Value = this.ID} 
                };


                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    return true;
                }
            }

            return false;
        }
        public bool Delete()
        {
            string execSql = "";
            execSql = "delete from T_Menus where  ID = @ID ";
            System.Data.OleDb.OleDbParameter par = new System.Data.OleDb.OleDbParameter("@ID", System.Data.OleDb.OleDbType.Integer) { Value = this.ID };

            string delServerConfigSql = "delete from T_ServerConfig where MemuId in ( select ID from T_Menus where ParentID = @ID )";
            string deldcsql = "delete from T_ServerConfig where MemuId = @ID";
            string delChildSql = " delete from  T_Menus where  ParentID = @ID ";

            OleDbConnection conn = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OleDbConnStr"].ConnectionString);
            conn.Open();

            //   开启事务   
            OleDbTransaction oledbTransaction = conn.BeginTransaction();
            try
            {
                UrlMapping urlmapping = new UrlMapping();
                if (string.IsNullOrEmpty(this.AlternateField3) || urlmapping.Delete(this.AlternateField3))
                {
                    //   将事务应用于Command   
                    OleDbCommand oledbCommand = new OleDbCommand();
                    oledbCommand.Connection = conn;
                    oledbCommand.Transaction = oledbTransaction;
                    oledbCommand.Parameters.Add(par);

                    if (this.ParentId == 0)
                    {
                        oledbCommand.CommandText = delServerConfigSql;
                        oledbCommand.ExecuteNonQuery();

                        oledbCommand.CommandText = delChildSql;
                        oledbCommand.ExecuteNonQuery();
                    }
                    else
                    {
                        oledbCommand.CommandText = deldcsql;
                        oledbCommand.ExecuteNonQuery();
                    }


                    oledbCommand.CommandText = execSql;
                    oledbCommand.ExecuteNonQuery();
                    //   利用sqlcommand进行数据操作   

                    //   成功提交   
                    oledbTransaction.Commit();
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                //   出错回滚   
                oledbTransaction.Rollback();
                CommonLib.Session.SaveLog(ex);
                return false;
            }
            finally
            {
                conn.Close();
            }
            return true;
        }
    }
}